<?php
/**
 * @title 415. 字符串相加 - 逐位相加
 * @author start2004
 */

class Solution {

    /**
     * @param String $num1
     * @param String $num2
     * @return String
     */
    function addStrings($num1, $num2) {
        /**
         * @since 2020-08-03 长度
         */
        $len1 = strlen($num1);
        $len2 = strlen($num2);

        /**
         * @since 2020-08-03 保证`num1`是较长字符串
         */
        if($len1 < $len2){
            list($num1, $num2) = [$num2, $num1];
            list($len1, $len2) = [$len2, $len1];
        } else {}

        /**
         * @since 2020-08-03 尾部对齐, 逐位相加
         */
        $add = 0;
        for($i1=$len1-1, $i2=$len2-1; $i2>=0; $i1--, $i2--){
            $sum = $num1[$i1]+$num2[$i2]+$add;
            $num1[$i1] = $sum%10;
            $add = ($sum-$num1[$i1])/10;
        }

        /**
         * @since 2020-08-03 num1, 处理add
         */
        if($add > 0){
            for (; $i1>=0; $i1--){
                if($num1[$i1]+$add == 10){
                    $num1[$i1] = "0";
                    $add = 1;
                } else {
                    $num1[$i1] = $num1[$i1]+$add;
                    $add = 0;
                    break;
                }
            }

            /**
             * @since 2020-08-03 收官
             */
            if($add == 1){
                $num1 = "1". $num1;
            } else {}
        } else {}

        /**
         * @return
         */
        return $num1;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.03.php
 */
$datas = [
    ["123", "45678"],
    ["1", "999"],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->addStrings($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
